// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, data } = event
  
  // 检查权限（仅管理员可操作写入操作）
  const userResult = await db.collection('users').where({
    openid: wxContext.OPENID
  }).get()
  
  const isAdmin = userResult.data.length > 0 && userResult.data[0].role === '管理员'
  
  // 如果不是管理员且操作不是读取操作，拒绝访问
  if (!isAdmin && action !== 'list' && action !== 'get') {
    return {
      success: false,
      message: '无操作权限，仅管理员可修改检查项'
    }
  }
  
  try {
    switch (action) {
      // 创建新检查项
      case 'create':
        return await createCheckItem(data)
      
      // 更新检查项
      case 'update':
        return await updateCheckItem(data)
      
      // 删除检查项
      case 'delete':
        return await deleteCheckItem(data.itemId)
      
      // 获取检查项列表
      case 'list':
        return await listCheckItems(data)
      
      // 获取单个检查项详情
      case 'get':
        return await getCheckItem(data.itemId)
      
      // 批量创建检查项
      case 'batchCreate':
        return await batchCreateCheckItems(data.items)
        
      // 更新检查项顺序
      case 'updateOrder':
        return await updateItemsOrder(data.items)
        
      default:
        return {
          success: false,
          message: '未知操作'
        }
    }
  } catch (error) {
    console.error('管理检查项操作失败', error)
    return {
      success: false,
      error: error
    }
  }
}

// 创建新检查项
async function createCheckItem(itemData) {
  // 基本验证
  if (!itemData.name || !itemData.maxScore) {
    return {
      success: false,
      message: '缺少必要字段'
    }
  }
  
  // 检查名称是否重复
  const exist = await db.collection('checkItems').where({
    name: itemData.name
  }).count()
  
  if (exist.total > 0) {
    return {
      success: false,
      message: '检查项名称已存在'
    }
  }
  
  // 获取当前最大的order值
  const maxOrderResult = await db.collection('checkItems')
    .orderBy('order', 'desc')
    .limit(1)
    .get()
  
  let order = 1
  if (maxOrderResult.data.length > 0) {
    order = (maxOrderResult.data[0].order || 0) + 1
  }
  
  // 创建新检查项
  const newItem = {
    name: itemData.name,
    description: itemData.description || '',
    maxScore: itemData.maxScore,
    weight: itemData.weight || 1,
    category: itemData.category || '默认类别',
    standard: itemData.standard || '',
    isRequired: itemData.isRequired === false ? false : true,
    order: itemData.order || order,
    createTime: new Date(),
    updateTime: new Date(),
    isActive: itemData.isActive === false ? false : true
  }
  
  const result = await db.collection('checkItems').add({
    data: newItem
  })
  
  return {
    success: true,
    itemId: result._id,
    message: '创建检查项成功'
  }
}

// 更新检查项
async function updateCheckItem(itemData) {
  // 更新字段
  const updateData = {}
  
  // 只更新提供的字段
  if (itemData.hasOwnProperty('name')) updateData.name = itemData.name
  if (itemData.hasOwnProperty('description')) updateData.description = itemData.description
  if (itemData.hasOwnProperty('maxScore')) updateData.maxScore = itemData.maxScore
  if (itemData.hasOwnProperty('weight')) updateData.weight = itemData.weight
  if (itemData.hasOwnProperty('category')) updateData.category = itemData.category
  if (itemData.hasOwnProperty('standard')) updateData.standard = itemData.standard
  if (itemData.hasOwnProperty('isRequired')) updateData.isRequired = itemData.isRequired
  if (itemData.hasOwnProperty('order')) updateData.order = itemData.order
  if (itemData.hasOwnProperty('isActive')) updateData.isActive = itemData.isActive
  
  updateData.updateTime = new Date()
  
  // 执行更新
  await db.collection('checkItems').doc(itemData._id).update({
    data: updateData
  })
  
  return {
    success: true,
    message: '更新检查项成功'
  }
}

// 删除检查项
async function deleteCheckItem(itemId) {
  // 检查是否被引用
  const checkResult = await db.collection('checks').where({
    'items.itemId': itemId
  }).count()
  
  if (checkResult.total > 0) {
    return {
      success: false,
      message: '检查项已被使用，无法删除。建议使用"设为不活跃"功能替代删除。'
    }
  }
  
  await db.collection('checkItems').doc(itemId).remove()
  
  return {
    success: true,
    message: '删除检查项成功'
  }
}

// 获取检查项列表
async function listCheckItems() {
  let query = db.collection('checkItems')
  
  // 按类别筛选
  if (params.category) {
    query = query.where({
      category: params.category
    })
  }
  
  // 按活跃状态筛选
  if (params.isActive !== undefined) {
    query = query.where({
      isActive: params.isActive
    })
  }
  
  // 设置排序
  if (params.orderBy) {
    const order = params.orderDesc ? 'desc' : 'asc'
    query = query.orderBy(params.orderBy, order)
  } else {
    // 默认按order排序
    query = query.orderBy('order', 'asc')
  }
  
  const result = await query.get()
  
  return {
    success: true,
    items: result.data
  }
}

// 获取单个检查项详情
async function getCheckItem(itemId) {
  try {
    const result = await db.collection('checkItems').doc(itemId).get()
    
    if (!result.data) {
      return {
        success: false,
        message: '检查项不存在'
      }
    }
    
    return {
      success: true,
      item: result.data
    }
  } catch (error) {
    return {
      success: false,
      message: '获取检查项详情失败',
      error: error
    }
  }
}

// 批量创建检查项
async function batchCreateCheckItems(items) {
  if (!Array.isArray(items) || items.length === 0) {
    return {
      success: false,
      message: '无效的检查项数据'
    }
  }
  
  // 获取当前最大的order值
  const maxOrderResult = await db.collection('checkItems')
    .orderBy('order', 'desc')
    .limit(1)
    .get()
  
  let startOrder = 1
  if (maxOrderResult.data.length > 0) {
    startOrder = (maxOrderResult.data[0].order || 0) + 1
  }
  
  const results = []
  const now = new Date()
  
  // 检查是否有重复的名称
  const existingNames = await db.collection('checkItems').get()
  const existingNameSet = new Set(existingNames.data.map(item => item.name))
  
  // 验证所有项目的总分是否等于100
  let totalMaxScore = 0
  for (const item of items) {
    totalMaxScore += (item.maxScore || 0)
  }
  
  // 如果总分不是100，调整每项的分数比例
  if (totalMaxScore !== 0 && totalMaxScore !== 100) {
    const factor = 100 / totalMaxScore
    items.forEach(item => {
      item.maxScore = Math.round(item.maxScore * factor)
    })
    
    // 处理舍入后可能不等于100的情况
    const adjustedTotal = items.reduce((sum, item) => sum + item.maxScore, 0)
    if (adjustedTotal !== 100) {
      const diff = 100 - adjustedTotal
      // 把差值加到最后一项或权重最高的项
      let maxWeightIndex = 0
      let maxWeight = 0
      items.forEach((item, index) => {
        if ((item.weight || 0) > maxWeight) {
          maxWeight = item.weight
          maxWeightIndex = index
        }
      })
      items[maxWeightIndex].maxScore += diff
    }
  }
  
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    
    // 检查名称是否重复
    if (existingNameSet.has(item.name)) {
      results.push({
        name: item.name,
        success: false,
        message: '检查项名称已存在'
      })
      continue
    }
    
    // 每创建一个新的检查项，添加到已存在名称集合中
    existingNameSet.add(item.name)
    
    // 设置初始状态
    const newItem = {
      name: item.name,
      description: item.description || '',
      weight: item.weight || (1 / items.length), // 默认平均分配权重
      category: item.category || '默认类别',
      standard: item.standard || '',
      isRequired: item.isRequired === false ? false : true,
      order: item.order || (startOrder + i),
      createTime: now,
      updateTime: now,
      isActive: item.isActive === false ? false : true
    }
    
    try {
      const result = await db.collection('checkItems').add({
        data: newItem
      })
      
      results.push({
        name: item.name,
        success: true,
        itemId: result._id,
        maxScore: newItem.maxScore
      })
    } catch (error) {
      results.push({
        name: item.name,
        success: false,
        message: '创建失败',
        error: error
      })
    }
  }
  
  return {
    success: true,
    results: results,
    message: `批量创建完成，成功: ${results.filter(r => r.success).length}，失败: ${results.filter(r => !r.success).length}`,
   
  }
}

// 更新检查项顺序
async function updateItemsOrder(items) {
  if (!Array.isArray(items) || items.length === 0) {
    return {
      success: false,
      message: '无效的数据'
    }
  }
  
  // 批量更新
  const updatePromises = items.map(item => {
    if (!item._id || item.order === undefined) {
      return Promise.resolve({
        success: false,
        message: '缺少ID或order值',
        item: item
      })
    }
    
    return db.collection('checkItems').doc(item._id).update({
      data: {
        order: item.order,
        updateTime: new Date()
      }
    }).then(() => {
      return {
        success: true,
        itemId: item._id
      }
    }).catch(error => {
      return {
        success: false,
        message: '更新失败',
        error: error,
        itemId: item._id
      }
    })
  })
  
  const results = await Promise.all(updatePromises)
  
  return {
    success: true,
    results: results,
    message: `批量更新顺序完成，成功: ${results.filter(r => r.success).length}，失败: ${results.filter(r => !r.success).length}`
  }
} 